package servlet;

import pojo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

@WebServlet(urlPatterns = {"/user"})//一个类只能响应一个请求
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<User> users = new ArrayList<>();
        //jdbc操作数据库 查询

        try {

            // Scanner
            Scanner sc = new Scanner(System.in);
            System.out.print("请输入你要查询的姓名：");
            String word = sc.next();

            Class.forName("com.mysql.cj.jdbc.Driver");

            // 2、获取连接 (url username password)
            String url = "jdbc:mysql://127.0.0.1:3306/jdbc?characterEncoding=utf-8";
            Connection connection = DriverManager.getConnection(url, "root", "06060512han");

            // 3、写sql
            String sql = "select * from student where name like ? ";

            // 4、预编译sql
            PreparedStatement preparedStatement = connection.prepareStatement(sql);

            // 5、有参数设置参数
            preparedStatement.setObject(1, "%" + word + "%");

            // 6、执行sql
            ResultSet resultSet = preparedStatement.executeQuery();

            // 7、遍历结果集
            while (resultSet.next()) {
                User user = new User();
                user.setId(resultSet.getInt(1));
                user.setPass(resultSet.getString(3));
                user.setUsername(resultSet.getString(2));
                users.add(user);

                //System.out.println(id + "-----" + name + "------" + pass);
            }
            //8.关闭资源
            resultSet.close();
            preparedStatement.close();
            connection.close();
            //把集合中数据存储到作用域中
            req.setAttribute("users", users);
            //打开页面
            req.getRequestDispatcher("/user.jsp").forward(req, resp);


        } catch (SQLException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }


    }
}
